<template>
  <el-button
    type="primary"
    size="small"
    :loading="loading"
    @click="handleAddToCart"
  >
    加入购物车
  </el-button>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessageBox } from 'element-plus'
import { useCartStore } from '@/stores/cart'

const props = defineProps<{
  bookId: number
  bookName: string
}>()

const loading = ref(false)
const cartStore = useCartStore()

const handleAddToCart = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要将《${props.bookName}》添加到购物车吗？`,
      '添加到购物车',
      {
        confirmButtonText: '添加到购物车',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    loading.value = true
    await cartStore.addToCart(props.bookId)
  } catch {
    // 用户取消操作
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.add-to-cart {
  display: inline-block;
}
</style>
